const serverAddress = window.location.origin + "/sf";

function setupLoginButton() {
  const loginButton = document.querySelector(".login-btn");
  if (!loginButton) return;
  loginButton.addEventListener("click", async () => {
    const loginInput = document.querySelector(".passwd-input-field");
    if (!loginInput) {
      alert("未找到输入框");
      return;
    }
    const passwd = loginInput.value.trim();
    if (!passwd) {
      alert("请输入管理员密码");
      return;
    }
    // 按钮置灰
    loginButton.disabled = true;
    const originalText = loginButton.innerText;
    loginButton.innerText = "登录中...";
    try {
      const formData = new FormData();
      formData.append("passwd", passwd);
      const response = await fetch(serverAddress + "/Login", {
        method: "POST",
        body: formData,
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const result = await response.json();
      if (result && result.code === 200) {
        window.location.href = serverAddress + "/Flow/Index";
      } else {
        alert(`操作异常: ${result.message || "未知错误"}`);
      }
    } catch (error) {
      console.error("操作失败:", error);
      alert(`操作异常: ${error.message}`);
    } finally {
      // 恢复按钮状态
      loginButton.disabled = false;
      loginButton.innerText = originalText;
    }
  });
}

document.addEventListener("DOMContentLoaded", function () {
  setupLoginButton();
});
